package com.epfresh.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.epfresh.R;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.universalimageloader.core.imageaware.ImageViewAware;
import com.epfresh.api.utils.T;
import com.epfresh.bean.CartGood;
import com.epfresh.bean.Dc;
import com.epfresh.bean.DeliveryDate;
import com.epfresh.bean.DeliveryModes;
import com.epfresh.bean.MarketCart;
import com.epfresh.global.BaseApplication;
import com.epfresh.utils.FormatUtil;
import com.epfresh.views.dialog.DeliveryDateDialog;
import com.epfresh.views.dialog.MarketDialog;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * Created by wzh on 2016/5/6.
 */
public class CartOrderExpandListAdapter extends BaseExpandableListAdapter implements View.OnClickListener, RadioGroup.OnCheckedChangeListener, MarketDialog.OnPositiveClickListener {

    public interface OnRadioGroupListener {
        public void onRadioGroup(int groupPosition, int childPosition, int index);
    }

    public interface OnMarketListener {
        public void onMarket(MarketCart cartGoods, String marketId);
    }


    public Context context;
    public ExpandableListView lv;

    public List<MarketCart> groupList;

    public boolean hasAddress = true;

    public boolean isHasAddress() {
        return hasAddress;
    }

    public void setHasAddress(boolean hasAddress) {
        this.hasAddress = hasAddress;
    }

    private AdapterView.OnItemClickListener onItemClickListener;
    private OnBottomClickListener onBottomClickListener;
    private OnNotifyDataSetChangedListener onNotifyDataSetChangedListener;
    OnRadioGroupListener onRadioGroupListener;
    OnRadioGroupListener onPaymentRadioGroupListener;

    OnMarketListener onMarketListener;
    OnDiscountListener onDiscountListener;

    public OnDiscountListener getOnDiscountListener() {
        return onDiscountListener;
    }

    public void setOnDiscountListener(OnDiscountListener onDiscountListener) {
        this.onDiscountListener = onDiscountListener;
    }

    public OnRadioGroupListener getOnPaymentRadioGroupListener() {
        return onPaymentRadioGroupListener;
    }

    public void setOnPaymentRadioGroupListener(OnRadioGroupListener onPaymentRadioGroupListener) {
        this.onPaymentRadioGroupListener = onPaymentRadioGroupListener;
    }

    public OnRadioGroupListener getOnRadioGroupListener() {
        return onRadioGroupListener;
    }

    public void setOnRadioGroupListener(OnRadioGroupListener onRadioGroupListener) {
        this.onRadioGroupListener = onRadioGroupListener;
    }

    public OnMarketListener getOnMarketListener() {
        return onMarketListener;
    }

    public void setOnMarketListener(OnMarketListener onMarketListener) {
        this.onMarketListener = onMarketListener;
    }

    public CartOrderExpandListAdapter(Context context, ExpandableListView lv, List<MarketCart> groupList) {
        this.context = context;
        this.groupList = groupList;
        this.lv = lv;
    }


    @Override
    public void notifyDataSetChanged() {
        if (onNotifyDataSetChangedListener != null) {
            onNotifyDataSetChangedListener.OnNotifyDataSetChangedListener(groupList.size());
        }
        expendList();
        super.notifyDataSetChanged();
    }


    public OnNotifyDataSetChangedListener getOnNotifyDataSetChangedListener() {
        return onNotifyDataSetChangedListener;
    }

    public void setOnNotifyDataSetChangedListener(OnNotifyDataSetChangedListener onNotifyDataSetChangedListener) {
        this.onNotifyDataSetChangedListener = onNotifyDataSetChangedListener;
    }

    public OnBottomClickListener getOnBottomClickListener() {
        return onBottomClickListener;
    }

    public void setOnBottomClickListener(OnBottomClickListener onBottomClickListener) {
        this.onBottomClickListener = onBottomClickListener;
    }

    @Override
    public int getGroupCount() {
        return groupList.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        MarketCart marketCart = groupList.get(groupPosition);
        List<CartGood> configs = marketCart.getProductList();
        int count = 0;
        if (configs != null) {
            count = configs.size();
        }

        if (count > 3 && !marketCart.isExpend()) {
            count = 3;
        }


        return count;
    }

    @Override
    public Object getGroup(int groupPosition) {
        return groupList.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {

        return groupList.get(groupPosition).getProductList().get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    /**
     * 组和子元素是否持有稳定的ID,也就是底层数据的改变不会影响到它们。
     *
     * @return
     * @see android.widget.ExpandableListAdapter#hasStableIds()
     */
    @Override
    public boolean hasStableIds() {
        return true;
    }

    /**
     * 获取显示指定组的视图对象
     *
     * @param groupPosition 组位置
     * @param isExpanded    该组是展开状态还是伸缩状态
     * @param convertView   重用已有的视图对象
     * @param parent        返回的视图对象始终依附于的视图组
     * @return
     * @see android.widget.ExpandableListAdapter#getGroupView(int, boolean, View,
     * ViewGroup)
     */
    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        ViewHolder vh = null;
        if (convertView == null) {
            vh = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.item_group_list_cart_order, null, false);

            vh.tv = (TextView) convertView.findViewById(R.id.tv_name);
            vh.rlDiscount = convertView.findViewById(R.id.rl_discount);

            convertView.setTag(vh);
        } else {
            vh = (ViewHolder) convertView.getTag();
        }
        convertView.setTag(R.id.item_key_position, groupPosition);
        convertView.setClickable(true);

        MarketCart cartGoods = groupList.get(groupPosition);

/*        if (cartGoods.getWholeSalesType() == 1) {todo:2018年11月15日18:07:52
            vh.tv.setText(cartGoods.getStoreOrMarketName());
        } else {
//            vh.tv.setText(cartGoods.getStoreOrMarketName());
            vh.tv.setText(cartGoods.getDistributionTitle());
        }*/
        vh.tv.setText(cartGoods.getStoreOrMarketName());

        String discountStr = cartGoods.getDiscountStr();
        if (discountStr != null && !"".equals(discountStr)) {
//            vh.rlDiscount.setVisibility(View.VISIBLE);
            vh.rlDiscount.setVisibility(View.GONE);

        } else {
            vh.rlDiscount.setVisibility(View.GONE);

        }


        vh.rlDiscount.setTag(R.id.item_key_position, groupPosition);
        vh.rlDiscount.setTag(R.id.item_key_status, discountStr);
        vh.rlDiscount.setOnClickListener(this);

        return convertView;
    }


    /**
     * 获取一个视图对象，显示指定组中的指定子元素数据。
     *
     * @param groupPosition 组位置
     * @param childPosition 子元素位置
     * @param isLastChild   子元素是否处于组中的最后一个
     * @param convertView   重用已有的视图(View)对象
     * @param parent        返回的视图(View)对象始终依附于的视图组
     * @return
     * @see android.widget.ExpandableListAdapter#getChildView(int, int, boolean, View,
     * ViewGroup)
     */
    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {

        convertView = getChildNormalView(groupPosition, childPosition, isLastChild, convertView, parent);


        return convertView;
    }

    @SuppressLint("SetTextI18n")
    public View getChildNormalView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        ChildViewHolder vh = null;
        if (convertView == null) {
            vh = new ChildViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.item_child_list_cart_order, null, false);

            vh.vMore = convertView.findViewById(R.id.rl_more);
            vh.ivMore = (ImageView) convertView.findViewById(R.id.iv_more);
            vh.tvMore = (TextView) convertView.findViewById(R.id.tv_more);
            vh.vDelivery = convertView.findViewById(R.id.rl_delivery);
            vh.vOther = convertView.findViewById(R.id.rl_market);
            vh.vPayment = convertView.findViewById(R.id.rl_payment);
            vh.vTime = convertView.findViewById(R.id.rl_time);
            vh.vLine = convertView.findViewById(R.id.v_line_2);
            vh.ivLogo = (ImageView) convertView.findViewById(R.id.iv_logo);
            vh.ivRight = (ImageView) convertView.findViewById(R.id.iv_right);

            //现货,预售标志
            vh.tvType = (TextView) convertView.findViewById(R.id.tv_type);
            vh.tvTitle = (TextView) convertView.findViewById(R.id.tv_title);
            vh.tvUnit = (TextView) convertView.findViewById(R.id.tv_unit);

            vh.tvTotalPrice = (TextView) convertView.findViewById(R.id.tv_total);

            vh.tvDetail = (TextView) convertView.findViewById(R.id.tv_detail_address);
            //vh.tvOther = (TextView) convertView.findViewById(R.id.tv_other_price);
            vh.tvTime = (TextView) convertView.findViewById(R.id.tv_time_detail);
            vh.tvTimeTitle = (TextView) convertView.findViewById(R.id.tv_time);
            vh.tvDelivery = (TextView) convertView.findViewById(R.id.tv_2);
            vh.tvPick = (TextView) convertView.findViewById(R.id.tv_1);
            vh.tvMerchantDelivery = (TextView) convertView.findViewById(R.id.tv_3);
//            vh.rg = (RadioGroup) convertView.findViewById(R.id.rg_delivery);

            vh.tvOnline = (TextView) convertView.findViewById(R.id.tv_payment_2);
            vh.tvOffline = (TextView) convertView.findViewById(R.id.tv_payment_1);
            vh.tvMarketTotalPrice = (TextView) convertView.findViewById(R.id.tv_total_price);
//            vh.rgPayment = (RadioGroup) convertView.findViewById(R.id.rg_payment);

            vh.vOverArea = convertView.findViewById(R.id.rl_tips);
            vh.vTotalPrice = convertView.findViewById(R.id.rl_total);

            vh.tvDiscount = (TextView) convertView.findViewById(R.id.tv_discount);
            vh.rlMerMsg = convertView.findViewById(R.id.rl_mer_msg);
            vh.vMerMsgArrow = convertView.findViewById(R.id.iv_mer_msg_arrow);
            vh.vMerMsgLine = convertView.findViewById(R.id.v_line_mer_msg);
            vh.tvMerMsg = (TextView) convertView.findViewById(R.id.tv_mer_msg);
            vh.tvMerMsgTitle = (TextView) convertView.findViewById(R.id.tv_mer_msg_title);
            vh.tvPromotion = (TextView) convertView.findViewById(R.id.tv_promotion);
            vh.ivCorner = (ImageView) convertView.findViewById(R.id.iv_corner);
            convertView.setTag(vh);
        } else {
            vh = (ChildViewHolder) convertView.getTag();
        }


        MarketCart cartGoods = groupList.get(groupPosition);
        List<CartGood> goods = cartGoods.getProductList();

        CartGood cartGood = goods.get(childPosition);

        String merMsg = cartGood.getMerMsg();

        if (merMsg != null && !"".equals(merMsg)) {
            vh.rlMerMsg.setVisibility(View.VISIBLE);
            String s = "<font color=\"#959595\">我的留言：</font>" + merMsg;
            vh.tvMerMsg.setText(Html.fromHtml(s));
            vh.vMerMsgArrow.setVisibility(View.VISIBLE);
        } else {
            vh.rlMerMsg.setVisibility(View.GONE);
            vh.tvMerMsg.setText("");
            vh.vMerMsgArrow.setVisibility(View.GONE);
        }

        vh.tvMerMsgTitle.setTag(R.id.item_key_position, groupPosition);
        vh.tvMerMsgTitle.setTag(R.id.item_key_status, childPosition);
        vh.tvMerMsgTitle.setOnClickListener(this);

        String salesType = cartGood.getSalesType();
        if ("1".equals(salesType)) {//现货
            vh.tvTimeTitle.setText("要求送达时间");
        } else {
            vh.tvTimeTitle.setText("预计送达时间");

        }

        int count = 0;
        boolean isLast = false;
        if (goods != null) {
            count = goods.size();
        }

        if (count > 3 && !cartGoods.isExpend()) {
            if (childPosition == 2) {
                isLast = true;
            }
        } else {
            if (childPosition == goods.size() - 1) {
                isLast = true;
            }
        }
        vh.vMerMsgLine.setVisibility(View.GONE);
        if (isLast) {
            if (goods.size() > 3) {
                vh.vMore.setVisibility(View.VISIBLE);
                if (merMsg != null && !"".equals(merMsg)) {
                    vh.vMerMsgLine.setVisibility(View.VISIBLE);
                }
            } else {
                vh.vMore.setVisibility(View.GONE);
            }
        } else {
            vh.vMore.setVisibility(View.GONE);
        }

        if (!cartGoods.isExpend()) {
            int cnt = goods.size() - 3;
            cnt = cnt > 0 ? cnt : 0;
            vh.tvMore.setText("查看其余" + cnt + "件商品");
            vh.ivMore.setImageResource(R.mipmap.down_arrow);
        } else {
            vh.tvMore.setText("收起列表");
            vh.ivMore.setImageResource(R.mipmap.up_arrow);
        }

        vh.tvMore.setTag(R.id.item_key_position, groupPosition);
        vh.tvMore.setTag(R.id.item_key_status, childPosition);
        vh.tvMore.setOnClickListener(this);
        vh.ivMore.setTag(R.id.item_key_position, groupPosition);
        vh.ivMore.setTag(R.id.item_key_status, childPosition);
        vh.ivMore.setOnClickListener(this);

        if (!isLast) {
            vh.vDelivery.setVisibility(View.GONE);
            vh.vOther.setVisibility(View.GONE);
            vh.vPayment.setVisibility(View.GONE);
            vh.vTime.setVisibility(View.GONE);
            vh.vLine.setVisibility(View.GONE);

            vh.vTotalPrice.setVisibility(View.GONE);
//            vh.vOverArea.setVisibility(View.GONE);
        } else {
//            vh.vTotalPrice.setVisibility(View.VISIBLE);
            vh.vTotalPrice.setVisibility(View.GONE);

            if (cartGoods.isDeliveryOverScope() && hasAddress) {
//                vh.vOverArea.setVisibility(View.VISIBLE);
                vh.vDelivery.setVisibility(View.GONE);
                vh.vOther.setVisibility(View.GONE);
                vh.vTime.setVisibility(View.GONE);
                vh.vLine.setVisibility(View.GONE);
            } else {
//                vh.vOverArea.setVisibility(View.GONE);
                vh.vDelivery.setVisibility(View.VISIBLE);
                if (cartGoods.getDeliveryList().get(0).getName().equals("商家配送")) {
                    vh.vOther.setVisibility(View.GONE);
                } else {
                    vh.vOther.setVisibility(View.VISIBLE);
                }
//                vh.vOther.setVisibility(View.VISIBLE);
                vh.vTime.setVisibility(View.GONE);
//                vh.vTime.setVisibility(View.VISIBLE);
                vh.vLine.setVisibility(View.VISIBLE);
            }

//            vh.vDelivery.setVisibility(View.VISIBLE);
//            vh.vPayment.setVisibility(View.VISIBLE);


            vh.tvDelivery.setVisibility(View.GONE);
            vh.tvPick.setVisibility(View.GONE);
            vh.tvMerchantDelivery.setVisibility(View.GONE);
            List<DeliveryModes> deliveryList = cartGoods.getDeliveryList();
            if (deliveryList != null) {
                for (int i = 0; i < deliveryList.size(); i++) {
                    DeliveryModes deliveryModes = deliveryList.get(i);
                    String code = deliveryModes.getCode();
                    String name = deliveryModes.getName();

                    if ("gatherDistribution".equals(code)) {//集单配送
                        vh.tvDelivery.setVisibility(View.VISIBLE);
                        vh.tvDelivery.setText(name);
                        vh.tvDelivery.setTag(R.id.item_key_view, code);

                    } else if ("selfDelivery".equals(code) && cartGoods.getWholeSalesType() == 1) {
                        vh.tvPick.setVisibility(View.VISIBLE);
                        vh.tvPick.setText(name);
                        vh.tvPick.setTag(R.id.item_key_view, code);

                    } else if ("merchantDelivery".equals(code)) {
                        vh.tvMerchantDelivery.setVisibility(View.VISIBLE);
                        vh.tvMerchantDelivery.setText(name);
                        vh.tvMerchantDelivery.setTag(R.id.item_key_view, code);
                    }
                }
            }

            vh.tvOnline.setVisibility(View.GONE);
            vh.tvOffline.setVisibility(View.GONE);
//            List<PaymentModes> payTypeList = cartGoods.getPayTypeList();
//            if (payTypeList != null) {
//
//                for (int i = 0; i < payTypeList.size(); i++) {
//                    PaymentModes paymentModes = payTypeList.get(i);
//                    String name = paymentModes.getName();
//                    if (i == 0) {
//                        vh.tvOnline.setText(name);
//                        vh.tvOnline.setVisibility(View.VISIBLE);
//                    } else if (i == 1) {
//                        vh.tvOffline.setText(name);
//                        vh.tvOffline.setVisibility(View.VISIBLE);
//                    }
//                }
//            }
        }


        String productTitle = cartGood.getProductTitle();
        if (productTitle == null) {
            productTitle = "";
        }


//        String s = context.getString(R.string.total_price, cartGood.getProductUnitPrice()) + "/" + cartGood.getProductChargeUnit();
//        String s = cartGood.getProductPriceUnit();
        String s = context.getString(R.string.total_price, cartGood.getProductUnitPrice()) + "/" + cartGood.getProductChargeUnit();
        if (cartGood.isPrePrice()) {
            vh.tvUnit.setText(context.getString(R.string.order_count, s, FormatUtil.subZeroAndDot(cartGood.getProductCount() + "")) + cartGood.getProductChargeUnit());
            vh.tvTotalPrice.setVisibility(View.VISIBLE);
        } else {
            vh.tvUnit.setText(context.getString(R.string.order_count, "时价", FormatUtil.subZeroAndDot(cartGood.getProductCount() + "")) + cartGood.getProductChargeUnit());
            vh.tvTotalPrice.setVisibility(View.GONE);
        }
        double total = FormatUtil.countMultiply(cartGood.getProductCount(), cartGood.getProductUnitPrice());
        vh.tvTotalPrice.setText(context.getString(R.string.total_price, total));

        ImageLoader.getInstance().displayImage(cartGood.getProductImgUrl(), vh.ivLogo);


//        vh.tvDelivery.setOnClickListener(this);
//        vh.tvPick.setOnClickListener(this);
        DeliveryDate defDeliveryDate = cartGoods.getDeliveryDateDef();

        if (defDeliveryDate != null) {
            vh.tvTime.setText(defDeliveryDate.getTitle());
        } else {
            vh.tvTime.setText("");
        }
        vh.vTime.setTag(R.id.item_key_position, groupPosition);
        vh.vTime.setTag(R.id.item_key_status, childPosition);
        vh.vTime.setOnClickListener(this);
        vh.vOther.setTag(R.id.item_key_position, groupPosition);
        vh.vOther.setTag(R.id.item_key_status, childPosition);
        if (cartGoods.isDeliverySelect() && vh.tvDelivery.getVisibility() == View.VISIBLE) {
//            vh.tvPick.setChecked(false);
//            vh.tvDelivery.setChecked(true);

            vh.tvDelivery.setBackgroundResource(R.drawable.checked_green_bg);
            vh.tvDelivery.setTextColor(context.getResources().getColor(R.color.green));
            vh.tvPick.setTextColor(Color.parseColor("#313131"));
            vh.tvPick.setBackgroundResource(R.drawable.checked_gray_bg);
            vh.tvMerchantDelivery.setTextColor(Color.parseColor("#313131"));
            vh.tvMerchantDelivery.setBackgroundResource(R.drawable.checked_gray_bg);


            vh.tvDetail.setText(cartGoods.getDistributionName());

//            vh.tvOther.setText(context.getString(R.string.fee_price, cartGoods.getFeed()));
            //vh.tvOther.setText(context.getString(R.string.fee_price, cartGoods.getProductExpressFeeOriginal()));
            vh.vOther.setOnClickListener(this);
            if (cartGoods.getWholeSalesType() == 1 && cartGoods.getDistributionList() != null && cartGoods.getDistributionList().size() > 1) {
                vh.ivRight.setVisibility(View.VISIBLE);
            } else {
                vh.ivRight.setVisibility(View.INVISIBLE);
            }
            if (!isLast) {
                vh.vTime.setVisibility(View.GONE);
            } else {
//                vh.vTime.setVisibility(View.VISIBLE);
                vh.vTime.setVisibility(View.GONE);
            }
        }else if (cartGoods.isMerchantDeliverySelect() && vh.tvMerchantDelivery.getVisibility() == View.VISIBLE){
            vh.tvMerchantDelivery.setBackgroundResource(R.drawable.checked_green_bg);
            vh.tvMerchantDelivery.setTextColor(context.getResources().getColor(R.color.green));
            vh.tvPick.setTextColor(Color.parseColor("#313131"));
            vh.tvPick.setBackgroundResource(R.drawable.checked_gray_bg);
            vh.tvDelivery.setTextColor(Color.parseColor("#313131"));
            vh.tvDelivery.setBackgroundResource(R.drawable.checked_gray_bg);

        } else {
//            vh.tvDelivery.setChecked(false);
//            vh.tvPick.setChecked(true);

            vh.tvPick.setTextColor(context.getResources().getColor(R.color.green));
            vh.tvDelivery.setTextColor(Color.parseColor("#313131"));
            vh.tvDelivery.setBackgroundResource(R.drawable.checked_gray_bg);
            vh.tvPick.setBackgroundResource(R.drawable.checked_green_bg);
            vh.tvMerchantDelivery.setTextColor(Color.parseColor("#313131"));
            vh.tvMerchantDelivery.setBackgroundResource(R.drawable.checked_gray_bg);


            vh.tvDetail.setText(cartGoods.getWholeSaleMarketFullName());
            //vh.tvOther.setText("");
            vh.vOther.setOnClickListener(null);
            vh.ivRight.setVisibility(View.INVISIBLE);
            vh.vTime.setVisibility(View.GONE);
        }


//        vh.rg.setTag(R.id.item_key_position, groupPosition);
//        vh.rg.setTag(R.id.item_key_status, childPosition);
//        vh.rg.setOnCheckedChangeListener(this);

//        vh.rgPayment.setTag(R.id.item_key_position, groupPosition);
//        vh.rgPayment.setTag(R.id.item_key_status, childPosition);
        vh.tvOnline.setTag(R.id.item_key_position, groupPosition);
        vh.tvOnline.setTag(R.id.item_key_status, childPosition);
        vh.tvOffline.setTag(R.id.item_key_position, groupPosition);
        vh.tvOffline.setTag(R.id.item_key_status, childPosition);

        vh.tvOnline.setOnClickListener(this);
        vh.tvOffline.setOnClickListener(this);

        vh.tvDelivery.setTag(R.id.item_key_position, groupPosition);
        vh.tvDelivery.setTag(R.id.item_key_status, childPosition);
        vh.tvPick.setTag(R.id.item_key_position, groupPosition);
        vh.tvPick.setTag(R.id.item_key_status, childPosition);
        vh.tvMerchantDelivery.setTag(R.id.item_key_position, groupPosition);

        vh.tvDelivery.setOnClickListener(this);
        vh.tvPick.setOnClickListener(this);
        vh.tvMerchantDelivery.setOnClickListener(this);

//        vh.rgPayment.setOnCheckedChangeListener(onCheckedChangeListener);

        if ("2".equals(cartGoods.getSalesType())) {//预售
            vh.tvType.setVisibility(View.VISIBLE);
//            vh.tvTitle.setText("               "+productTitle);
            String html = "<font color=\"#00f4f5f6\">【预售】a" + "</font>" + productTitle;
            vh.tvTitle.setText(Html.fromHtml(html));
        } else {

            vh.tvType.setVisibility(View.GONE);
            vh.tvTitle.setText(productTitle);
        }

        Double economizePrice = cartGoods.getEconomizePrice();
        if (economizePrice != null) {
//            vh.tvDiscount.setVisibility(View.VISIBLE);
            vh.tvDiscount.setVisibility(View.GONE);
            vh.tvDiscount.setText("已省" + context.getString(R.string.total_price, Math.abs(economizePrice)));

        } else {
            vh.tvDiscount.setText("");
            vh.tvDiscount.setVisibility(View.GONE);

        }


        if (hasAddress) {
            vh.tvDelivery.setEnabled(true);
            vh.tvPick.setEnabled(true);
            vh.tvMerchantDelivery.setEnabled(true);

        } else {
            vh.tvDelivery.setEnabled(false);
            vh.tvPick.setEnabled(false);
            vh.tvMerchantDelivery.setEnabled(false);
            vh.tvPick.setTextColor(Color.parseColor("#ffffff"));
            vh.tvDelivery.setTextColor(Color.parseColor("#ffffff"));
            vh.tvMerchantDelivery.setTextColor(Color.parseColor("#ffffff"));
            vh.tvDelivery.setBackgroundResource(R.drawable.enable_tag_bg);
            vh.tvPick.setBackgroundResource(R.drawable.enable_tag_bg);
            vh.tvMerchantDelivery.setBackgroundResource(R.drawable.enable_tag_bg);
//            vh.tvDelivery.setVisibility(View.GONE);
        }

        vh.tvMarketTotalPrice.setText(context.getString(R.string.total_price, getMarketTotalGoodsPriceFee(cartGoods)));
//        vh.tvMarketTotalPrice.setText(context.getString(R.string.total_price, cartGoods.getProductExpressFeeOriginal()));
        String promotionType = cartGood.getPromotionType();

        if ("1".equals(promotionType)) {//1促销2秒杀
            vh.tvPromotion.setBackgroundResource(R.drawable.activity_type_bg_orange);
            vh.tvPromotion.setVisibility(View.VISIBLE);
            vh.tvPromotion.setText("促");
            vh.tvPromotion.setTextColor(Color.parseColor("#fa7922"));
        } else if ("2".equals(promotionType)) {//1促销2秒杀
            vh.tvPromotion.setVisibility(View.VISIBLE);
            vh.tvPromotion.setText("秒");
            vh.tvPromotion.setTextColor(Color.parseColor("#40acea"));
            vh.tvPromotion.setBackgroundResource(R.drawable.activity_type_bg_blue);
        } else {
            vh.tvPromotion.setVisibility(View.GONE);
        }
        String promotionMarkUrl = cartGood.getMarkUrl();
        ImageLoader.getInstance().displayImage(promotionMarkUrl, new ImageViewAware(vh.ivCorner), BaseApplication.getTagOptions(promotionMarkUrl), null, null, null);

        return convertView;
    }


    RadioGroup.OnCheckedChangeListener onCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            int groupPosition = (int) radioGroup.getTag(R.id.item_key_position);
            int childPosition = (int) radioGroup.getTag(R.id.item_key_status);
            TextView tv1 = (TextView) radioGroup.findViewById(R.id.tv_payment_1);
            TextView tv2 = (TextView) radioGroup.findViewById(R.id.tv_payment_2);

            int index = -1;
            if (i == R.id.tv_payment_1) {


                index = 1;
            } else if (i == R.id.tv_payment_2) {
                index = 2;
            }


            MarketCart cartGoods = groupList.get(groupPosition);


            radioGroup.setOnCheckedChangeListener(null);

            notifyDataSetChanged();
            if (onPaymentRadioGroupListener != null) {
                onPaymentRadioGroupListener.onRadioGroup(groupPosition, childPosition, index);
            }

        }
    };

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        int groupPosition = (int) radioGroup.getTag(R.id.item_key_position);
        int childPosition = (int) radioGroup.getTag(R.id.item_key_status);
        TextView tv1 = (TextView) radioGroup.findViewById(R.id.tv_1);
        TextView tv2 = (TextView) radioGroup.findViewById(R.id.tv_2);

//        if ("gatherDistribution".equals(tv2.getTag(R.id.item_key_view))){//1号绑定的是
//
//        }else if ("gatherDistribution".equals(tv1.getTag(R.id.item_key_view))){
//
//        }
//
//        if ("selfDelivery".equals(tv1.getTag(R.id.item_key_view))){
//
//        }else if ("selfDelivery".equals(tv2.getTag(R.id.item_key_view))){
//
//        }

        int index = -1;
        if (i == R.id.tv_1) {//自提


            index = 1;
        } else if (i == R.id.tv_2) {//集单配送
            index = 2;
        }


        MarketCart cartGoods = groupList.get(groupPosition);
//                List<CartGood> goods = cartGoods.getResult();
//
//                CartGood cartGood = goods.get(childPosition);
        if (index == 1) {//自提
            cartGoods.setDeliverySelect(false);
        } else if (index == 2) {//集单配送
            cartGoods.setDeliverySelect(true);
        }
        notifyDataSetChanged();
        if (onRadioGroupListener != null) {
            onRadioGroupListener.onRadioGroup(groupPosition, childPosition, index);
        }

    }

    OnMerMsgListener onMerMsgListener;

    public OnMerMsgListener getOnMerMsgListener() {
        return onMerMsgListener;
    }

    public void setOnMerMsgListener(OnMerMsgListener onMerMsgListener) {
        this.onMerMsgListener = onMerMsgListener;
    }

    @Override
    public void onClick(View v) {


        Object tag = v.getTag(R.id.item_key_position);
        if (tag != null && tag instanceof Integer) {
            int position = (int) tag;

            switch (v.getId()) {

                case R.id.rl_market:

                    MarketCart cartGoods = groupList.get(position);
                    String wholeSaleMarketId = cartGoods.getWholeSaleMarketId();
                    if (wholeSaleMarketId != null && cartGoods.getDistributionList() != null && cartGoods.getDistributionList().size() > 1) {
                        openMarketDialog(cartGoods.getDistributionList(), cartGoods, cartGoods.getDistributionId());
//                        requestDc(wholeSaleMarketId, cartGoods.getDistributionId(), cartGoods);
                    } else {
                        T.toast("没有更多配送中心");
                    }
                    break;
                case R.id.rl_time:

                    MarketCart cartGoods2 = groupList.get(position);
                    DeliveryDate deliveryDateDef = cartGoods2.getDeliveryDateDef();
                    List<DeliveryDate> deliveryDate = cartGoods2.getDeliveryDateList();
                    if (deliveryDate == null || deliveryDate.size() < 1) {
                        T.toast("没有更多时间");
                    } else {
                        String id = "";
                        if (deliveryDateDef != null) {
                            id = deliveryDateDef.getId();
                        }
                        openDeliveryDateDialog(deliveryDate, cartGoods2, id);
                    }

                    break;
                case R.id.tv_3:
                    MarketCart cartGoods4 = groupList.get(position);
                    cartGoods4.setMerchantDeliverySelect(true);
                    cartGoods4.setDeliverySelect(false);
                    notifyDataSetChanged();
                    break;
                case R.id.tv_2:
                    MarketCart cartGoods5 = groupList.get(position);
                    cartGoods5.setDeliverySelect(true);
                    cartGoods5.setMerchantDeliverySelect(false);
                    notifyDataSetChanged();
                    if (onRadioGroupListener != null) {
                        int childPosition = (int) v.getTag(R.id.item_key_status);
                        onRadioGroupListener.onRadioGroup(position, childPosition, 2);
                    }
                    break;
                case R.id.tv_1:
                    MarketCart cartGoods6 = groupList.get(position);
                    cartGoods6.setDeliverySelect(false);
                    cartGoods6.setMerchantDeliverySelect(false);
                    notifyDataSetChanged();
                    if (onRadioGroupListener != null) {
                        int childPosition2 = (int) v.getTag(R.id.item_key_status);
                        onRadioGroupListener.onRadioGroup(position, childPosition2, 1);
                    }
                    break;
                case R.id.tv_more:
                case R.id.v_more:
                case R.id.iv_more:
                    MarketCart cartGoods7 = groupList.get(position);
                    boolean expend = cartGoods7.isExpend();
                    cartGoods7.setExpend(!expend);
                    notifyDataSetChanged();
                    break;
                case R.id.rl_discount:
                    if (onDiscountListener != null) {
                        Object tag1 = v.getTag(R.id.item_key_status);
                        String s = null;
                        if (tag1 != null && tag1 instanceof String) {
                            s = (String) tag1;
                        }
                        onDiscountListener.onDiscountListener(position, s);
                    }
                    break;
                case R.id.tv_mer_msg_title:
                    if (onMerMsgListener != null) {
                        if (position < groupList.size()) {
                            MarketCart cartGoods8 = groupList.get(position);
                            int childPosition = (int) v.getTag(R.id.item_key_status);
                            List<CartGood> pl = cartGoods8.getProductList();
                            if (pl != null && childPosition < pl.size()) {
                                onMerMsgListener.onMerMsgListener(position, childPosition, pl.get(childPosition));
                            }
                        }
                    }
                    break;

            }


        }
    }


    public double getTotalFee() {
        double fee = 0;
        BigDecimal bd = new BigDecimal(fee);
        for (int i = 0; i < groupList.size(); i++) {

            MarketCart cartGoods = groupList.get(i);
            if (cartGoods.isDeliverySelect() && !cartGoods.isOverScope()) {
//                fee += cartGoods.getFeed();

//                BigDecimal bd1 = new BigDecimal(cartGoods.getFeed());
                BigDecimal bd1 = new BigDecimal(cartGoods.getProductExpressFeeOriginal());
                bd = bd.add(bd1);
//                fee = FormatUtil.countAdd(fee,cartGoods.getFeed());
            }
        }
        fee = bd.setScale(2, RoundingMode.HALF_UP).doubleValue();
        return fee;
    }

    public double getRealFee() {
        double fee = 0;
        BigDecimal bd = new BigDecimal(fee);
        for (int i = 0; i < groupList.size(); i++) {

            MarketCart cartGoods = groupList.get(i);
            if (cartGoods.isDeliverySelect() && !cartGoods.isOverScope()) {
//                fee += cartGoods.getFeed();

//                BigDecimal bd1 = new BigDecimal(cartGoods.getProductExpressFee());
                BigDecimal bd1 = new BigDecimal(cartGoods.getProductExpressFee());
                bd = bd.add(bd1);
//                fee = FormatUtil.countAdd(fee,cartGoods.getFeed());
            }
        }
        fee = bd.setScale(2, RoundingMode.HALF_UP).doubleValue();
        return fee;
    }

    public double getTotalReduceFee() {
        double fee = 0;
        BigDecimal bd = new BigDecimal(fee);
        for (int i = 0; i < groupList.size(); i++) {

            MarketCart cartGoods = groupList.get(i);
            if (cartGoods.isDeliverySelect() && !cartGoods.isOverScope()) {
//                fee += cartGoods.getFeed();

                Double productExpressFeeReduce = cartGoods.getProductExpressFeeReduce();
                if (productExpressFeeReduce != null) {
                    BigDecimal bd1 = new BigDecimal(productExpressFeeReduce);
                    bd = bd.add(bd1);
                }
//                fee = FormatUtil.countAdd(fee,cartGoods.getFeed());
            }
        }
        fee = bd.setScale(2, RoundingMode.HALF_UP).doubleValue();
        return fee;
    }

    public boolean isHasSelf() {
        for (int i = 0; i < groupList.size(); i++) {
            MarketCart cartGoods = groupList.get(i);
            if (!cartGoods.isDeliverySelect()) {
                return true;
            }
        }
        return false;
    }


    public float getTotalOnlinePrice() {

//        for (int i = 0; i < list.size(); i++) {
//            MarketCart cartGoods = list.get(i);
//            if (cartGoods.isPaymentFirst()) {
//                List<PaymentModes> payTypeList = cartGoods.getPayTypeList();
//                if (payTypeList != null && payTypeList.size() > 0) {
//                    PaymentModes paymentModes = payTypeList.get(0);
//                    String code = paymentModes.getCode();
//                    if ("onlinePayment".equals(code)) {
//                        List<CartGood> result = cartGoods.getResult();
//                        if (result != null) {
//                            for (CartGood cartGood : result)
//                                total += cartGood.getProductUnitPrice() * cartGood.getProductCount();
//                        }
//                    }
//                }
//
//            } else {
//                List<PaymentModes> payTypeList = cartGoods.getPayTypeList();
//                if (payTypeList != null && payTypeList.size() > 1) {
//                    PaymentModes paymentModes = payTypeList.get(1);
//                    String code = paymentModes.getCode();
//                    if ("onlinePayment".equals(code)) {
//                        List<CartGood> result = cartGoods.getResult();
//                        if (result != null) {
//                            for (CartGood cartGood : result)
//                                total += cartGood.getProductUnitPrice() * cartGood.getProductCount();
//                        }
//                    }
//                }
//
//            }
//        }

        return (float) 0;
    }

    //商品总价
    public double getTotalGoodsPrice() {
        double total = 0;

        for (int i = 0; i < groupList.size(); i++) {
            MarketCart cartGoods = groupList.get(i);

            List<CartGood> result = cartGoods.getProductList();
            if (result != null) {
                BigDecimal bd = new BigDecimal(total);
                for (CartGood cartGood : result) {
                    BigDecimal bd1 = new BigDecimal(cartGood.getProductUnitPrice()).setScale(2, RoundingMode.HALF_UP);
                    BigDecimal bd2 = new BigDecimal(cartGood.getProductCount()).setScale(2, RoundingMode.HALF_UP);


                    bd = bd.add(bd1.multiply(bd2).setScale(2, RoundingMode.HALF_UP));
//                    total = FormatUtil.countAdd(total, FormatUtil.countMultiply(cartGood.getProductUnitPrice(), cartGood.getProductCount()));
                }
                total = bd.setScale(2, RoundingMode.HALF_UP).doubleValue();
            }

        }

        return total;
    }

    public double getMarketTotalGoodsFee(MarketCart cartGoods) {
        double fee = 0;
        BigDecimal bd = new BigDecimal(fee).setScale(2, RoundingMode.HALF_UP);


        if (cartGoods.isDeliverySelect() && !cartGoods.isOverScope()) {
//                fee += cartGoods.getFeed();

            BigDecimal bd1 = new BigDecimal(cartGoods.getFeed()).setScale(2, RoundingMode.HALF_UP);
            bd = bd.add(bd1);
//                fee = FormatUtil.countAdd(fee,cartGoods.getFeed());
        }

        fee = bd.setScale(2, RoundingMode.HALF_UP).doubleValue();
        return fee;
    }

    public double getMarketTotalGoodsPriceFee(MarketCart cartGoods) {
//        double fee = getMarketTotalGoodsFee(cartGoods);
        double fee = 0;
        if (cartGoods.isDeliverySelect() && !cartGoods.isOverScope()) {
            fee = cartGoods.getProductExpressFeeOriginal();
        } else {
            fee = 0;
        }
        double price = getMarketTotalGoodsPrice(cartGoods);
        return new BigDecimal(fee).add(new BigDecimal(price)).setScale(2, RoundingMode.HALF_UP).doubleValue();
    }

    public double getMarketTotalGoodsPrice(MarketCart cartGoods) {
        double total = 0;
        List<CartGood> result = cartGoods.getProductList();
        if (result != null) {
            BigDecimal bd = new BigDecimal(total);
            for (CartGood cartGood : result) {
                BigDecimal bd1 = new BigDecimal(cartGood.getProductUnitPrice()).setScale(2, RoundingMode.HALF_UP);
                BigDecimal bd2 = new BigDecimal(cartGood.getProductCount()).setScale(2, RoundingMode.HALF_UP);


                bd = bd.add(bd1.multiply(bd2).setScale(2, RoundingMode.HALF_UP));
//                total = FormatUtil.countAdd(total,FormatUtil.countMultiply(cartGood.getProductUnitPrice(),cartGood.getProductCount()));
                Log.e("total", "total--:" + bd.setScale(2, RoundingMode.HALF_UP).doubleValue());
                Log.e("total", "total--:" + bd);

                Log.e("total", "total--1:" + bd1);
                Log.e("total", "total--2:" + bd2);
//                total += cartGood.getProductUnitPrice() * cartGood.getProductCount();
            }
            total = bd.setScale(2, RoundingMode.HALF_UP).doubleValue();
            Log.e("total", "total:" + total);
        }
        return total;
    }

    public double getTotalPrice() {
        double total = FormatUtil.countAdd(getTotalFee(), getTotalGoodsPrice());

        return total;
    }


    /**
     * 是否选中指定位置上的子元素。
     *
     * @param groupPosition
     * @param childPosition
     * @return
     * @see android.widget.ExpandableListAdapter#isChildSelectable(int, int)
     */
    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return false;
    }


    protected void expendList() {

        if (lv != null)
            for (int i = 0; i < groupList.size(); i++) {
                lv.expandGroup(i);
            }
    }

    public float calTotalPrice() {

        float total = 0;
//        for (int i = 0; i < list.size(); i++) {
//            CartGoods cartGoods = list.get(i);
//
//            List<CartGood> list = cartGoods.getResult();
//            if (list != null && list.size() > 0) {
//                for (int j = 0; j < list.size(); j++) {
//                    CartGood cartGood = list.get(j);
//                    if (cartGood.isSelect()) {
//                        float productUnitPrice = cartGood.getProductUnitPrice();
//                        int productCount = cartGood.getProductCount();
//                        total += productUnitPrice * productCount;
//                    }
//                }
//            }
//        }


        return total;

    }


    public class ViewHolder {

        TextView tv;
        View rlDiscount;

    }

    public class ChildViewHolder {

        ImageView ivLogo;
        ImageView ivRight;

        TextView tvTitle;
        TextView tvUnit;
        TextView tvType;
        TextView tvTime;
        TextView tvTimeTitle;
        TextView tvPayment;
        TextView tvTotalPrice;


        TextView tvDelivery;
        TextView tvPick;
        TextView tvMerchantDelivery;
        TextView tvMore;
        ImageView ivMore;
        //        RadioGroup rg;
        TextView tvDetail;
        //TextView tvOther;
        TextView tvMarketTotalPrice;

        View vMore;
        View vDelivery;
        View vOther;
        View vPayment;
        View vTime;
        View vLine;
        View vOverArea;
        View vTotalPrice;


        TextView tvOnline;
        TextView tvOffline;

        TextView tvDiscount;

        //
        TextView tvMerMsgTitle;
        TextView tvMerMsg;
        TextView tvPromotion;
        View rlMerMsg;
        View vMerMsgArrow;
        View vMerMsgLine;
        ImageView ivCorner;
    }


    public interface OnBottomClickListener {

        public void onBottomClickListener(int position, int type);
    }

    public interface OnNotifyDataSetChangedListener {

        public void OnNotifyDataSetChangedListener(int size);
    }


    MarketDialog marketDialog;

    public void openMarketDialog(List<Dc> markets, Object o, String distributionId) {
        if (marketDialog == null) {
            marketDialog = new MarketDialog(context);
            marketDialog.setOnPositiveClickListener(this);
        }

        marketDialog.setO(o);
        marketDialog.setPositiveDismiss(true);
        marketDialog.setCurrent(markets, distributionId);
        marketDialog.show();
    }

    DeliveryDateDialog deliveryDateDialog;

    public void openDeliveryDateDialog(List<DeliveryDate> markets, Object o, String distributionId) {
        Log.e("adapter", "dialog_________________");
        if (deliveryDateDialog == null) {
            deliveryDateDialog = new DeliveryDateDialog(context);
            deliveryDateDialog.setOnPositiveClickListener(new DeliveryDateDialog.OnPositiveClickListener() {
                @Override
                public void onPositiveClickListener(Object o, DeliveryDate market) {
                    if (o != null) {
                        ((MarketCart) o).setDeliveryDateDef(market);
                        notifyDataSetChanged();
                    }
                }
            });
        }

        deliveryDateDialog.setO(o);
        deliveryDateDialog.setPositiveDismiss(true);
        deliveryDateDialog.setCurrent(markets, distributionId);
        deliveryDateDialog.show();
    }

    @Override
    public void onPositiveClickListener(Object o, Dc market) {

        if (o != null) {
            ((MarketCart) o).setDistributionId(market.getId());
            ((MarketCart) o).setDistributionName(market.getTitle());

            if (onMarketListener != null) {
                onMarketListener.onMarket(((MarketCart) o), market.getId());
            }
            notifyDataSetChanged();
        }

    }

    public interface OnDiscountListener {
        public void onDiscountListener(int position, String data);
    }

    public interface OnMerMsgListener {
        public void onMerMsgListener(int groupPosition, int position, CartGood data);
    }

}
